import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from './store';
import { Layout, Table, Input, Button, InputNumber, Popconfirm, Space } from 'antd';

import UploadFile from './components/uploadFile';
import './style.scss';

import {downloadFileAxios} from '../../../api/dataSource/fileManage'

const { Content } = Layout;

@withRouter
class FileManagement extends Component{
  state={
    page: 10,
    searchValue: '',
  };

  changePage = (value) => {
    this.setState({page:value});
  }
  
  setSearchValue = (e) => {
    this.setState({searchValue: e.target.value})
  }

  handleSearch = () => {
    this.props.getAllFilesSearch(this.state.searchValue)
    this.setState({searchValue: ''})
  }

  resetSearch = () => {
    this.setState({searchValue:''});
    this.props.getAllFiles();
  }

  componentDidMount(){
    this.props.getAllFiles()
  };

  downloadFile = (fileId, filename) => {
    downloadFileAxios({fileId, filename}).then(res=>{
      var blob = res.data;
      // FileReader主要用于将文件内容读入内存
      var reader = new FileReader();
      reader.readAsDataURL(blob);
      // onload当读取操作成功完成时调用
      reader.onload = function(e) {
        var a = document.createElement('a');
        a.download = filename;
        a.href = e.target.result;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
    })
  }

  render(){
    const { page } = this.state;
    const columns = [
      {
        title: "序号", 
        key: 'dataIndex',
        render:(text, record, index)=><span>{index+1}</span>
      },{
        title: "文件名称",
        key: "filename",
        dataIndex: 'filename',
        render: (text)=>{
          return text.slice(0,text.lastIndexOf('.'))
        }
      },{
        title: '文件类型',
        key: "filename",
        dataIndex: 'filename',
        render: (text)=>{
          return text.slice(text.lastIndexOf('.')+1)
        }
      },{
        title: '目录地址',
        key: 'path',
        dataIndex: 'path',
        render: (text)=>{
          return text.slice(0,text.lastIndexOf('/'))
        }
      },{
        title: '上传时间',
        key: 'createTime',
        dataIndex: 'createTime'
      },{
        title: '操作',
        key: 'operation',
        render: (text, record)=>(
            <Space>
              <a  onClick={e=>{e.stopPropagation(); this.downloadFile(record.id, record.filename)}}>下载</a>
              <Popconfirm
              title="删除后数据将无法恢复，确认删除吗?"
              onConfirm={() => this.props.deleteFile(record.id, record.filename)}
              >
                <a>删除</a>
              </Popconfirm>
            </Space>)
      }
    ]
    return (
      <Content style={{marginTop:12}}>
        <div>
          <div style={{display: 'inline-block', fontWeight: 'bold'}}>数据源文件列表</div>
          <div style={{float: 'right', display: 'inline-block', height:'100%'}}>
            <span>关键字: <Input placeholder="请输入文件名/目录" style={{width: 200}} onChange={this.setSearchValue} value={this.state.searchValue}/></span>
            <Button type="primary" style={{marginLeft: 12}} onClick={this.handleSearch} disabled={!this.state.searchValue}>搜索</Button>
            <Button type="primary" style={{marginLeft: 12}} onClick={this.resetSearch}>重置</Button>
            <UploadFile/>
          </div>
        </div>
        <div className="table-box" style={{marginTop:24}}>
          <Table pagination={{pageSize:page,showSizeChanger:false}} dataSource={this.props.files} columns={columns} />
          <div className={this.props.files.length>0?'footer':'withoutPagination'}>
            显示<InputNumber min={1} defaultValue={page} onChange={this.changePage}/>项结果，共{this.props.files.length}项
          </div>
        </div>
      </Content>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    files: state.getIn(['file','files']).toJS(),
  }
}

const mapDispatchToProps = (dispatch) => ({
  getAllFiles(){
    dispatch(actionCreators.getFilesOperation())
  },
  getAllFilesSearch(search){
    dispatch(actionCreators.getFilesSearch(search))
  },
  deleteFile(id, name){
    dispatch(actionCreators.deleteFile(id, name))
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(FileManagement);